package light.mvc.utils;

import java.beans.PropertyDescriptor;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.beanutils.PropertyUtilsBean;

public class StringUtil {

	/**
	 * 格式化字符串
	 * 
	 * 例：formateString("xxx{0}bbb",1) = xxx1bbb
	 * 
	 * @param str
	 * @param params
	 * @return
	 */
	public static String formateString(String str, String... params) {
		for (int i = 0; i < params.length; i++) {
			str = str.replace("{" + i + "}", params[i] == null ? "" : params[i]);
		}
		return str;
	}
	
	public static Map<String, Object> map = 
		new HashMap<String, Object>();
	
	public static String getParams(Object obj){
		StringBuilder sb = new StringBuilder(" where 1=1 "); 
		try {
			Map<String, Object> map = beanToMap(obj);
			//遍历map
			for(String key:map.keySet()){
				
				sb.append(" and "+ getTbColumn(key) + "= '"+map.get(key)+"' ");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return sb.toString();
	}
	
	public static String getHql(String model,Object obj){
		StringBuilder sb = new StringBuilder("from "+ model +" where 1=1 ");
		try {
			//获取对象里有值的属性map
			Map<String, Object> map = beanToMap(obj);
			//遍历map
			for(String key:map.keySet()){
				String formate = "yyyy-mm-dd hh24:mi:ss";
				String rs = formate;
				//判断特殊的开始时间
				if("startTime".equals(key)){
					//获取时间
					String startTime = map.get(key)+"";
					//判断长度，和截取适当的长度
					if(startTime.length()<=10){
						rs = formate.substring(0, startTime.length());
					}
					//拼接oracle数据库查询时间的格式
					sb.append(" and createDate >= to_date(:"+key+",'"+rs+"')" );
					continue;
				}
				if("endTime".equals(key)){
					String endTime = map.get(key)+"";
					if(endTime.length()<=10){
						rs = formate.substring(0, endTime.length());
					}
					sb.append(" and createDate <= to_date(:"+key+",'"+rs+"')" );
					continue;
				}
				//判断特殊字段mark
				if("mark".equals(key)){
					String mark = map.get(key)+"";
					if("gt".equals(mark)){
						mark = ">=";
					}else if("lt".equals(mark)){
						mark = "<=";
					}else{
						mark = "=";
					}
					sb.append(" and score "+mark+" :score");
					continue;
				}
				//上面已经处理score,不需要重复添加
				if("score".equals(key)){
					continue;
				}
				//循环追加查询条件
				sb.append(" and "+key+" = :"+key);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return sb.toString();
	}
	
	public static Map<String, Object> getMap(Object obj){
		Map<String, Object> map = 
			new HashMap<String, Object>();
		try{
			for(String key:beanToMap(obj).keySet()){
				map.put(key, beanToMap(obj).get(key));
			}
		}catch (Exception e) {
			e.printStackTrace();
		}
		return map;
	}
	
	
	public static String getTbColumn(String key){
		//存储新字符串的sb
		StringBuilder sb = new StringBuilder();
		//正则表达式
		String regex = "[A-Z]";
		//遍历字符串
		for(int i=0;i<key.length();i++){
			//获取字符串的每一个字符，且转换成字符串
			String s = key.charAt(i)+"";
			//判断是否为大小字母
			if(i>0&&s.matches(regex)){
				//追加下划线
				sb.append("_");
			}
			//追加小写字母
			sb.append(s.toLowerCase());
		}
		return sb.toString();
	}
	
	public static Map<String, Object> beanToMap(Object obj){
		
		//存储有值的属性
		Map<String, Object> map = 
			new HashMap<String, Object>();
		
		try {
			
			//声明bean属性读取对象
			PropertyUtilsBean pub = new PropertyUtilsBean();
			//把bean的属性读取到一个数组中(descriptor)
			PropertyDescriptor pd[] =
				pub.getPropertyDescriptors(obj);
			//循环遍历属性，获取属性对应的值
			for(int i=0;i<pd.length;i++){
				//获取属性名
				String name = pd[i].getName();
				
				//排除构造函数
				if(!name.equals("class")
						&&!name.equals("pageNow")
						&&!name.equals("pageSize")
						&&!name.equals("pageStart")){
					//获取属性对应的值，没有明确数据类型，用Object
					Object value = pub.getNestedProperty(obj, name);
					//判断值是否为空，不为空的就添加到map
					if(value!=null&&!value.equals("")){
						//输出值是什么数据类型
						//判断为时间
						if(value.getClass()==Date.class)
							value = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
									.format(value);
						//添加到map
						map.put(name, value);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return map;
		
	}
	
	public static String getInsert
	(Object obj,String tableName){
		StringBuilder sb = new StringBuilder();
		try {
			
			Map<String, Object> map = beanToMap(obj);
			//判断是否有插入的字段
			if(map.keySet().size()>0){
				//insert into  tableName () values () 
				//判断是否 添加，号
				boolean b = false;
				sb = new StringBuilder("insert into "+ tableName);
				//拼接插入列
				StringBuilder s1 = new StringBuilder(" (");
				//拼接插入值
				StringBuilder s2 = new StringBuilder(" (");
				//遍历map
				for(String key:map.keySet()){
					if(b){
						s1.append(",");
						s2.append(",");
					}
					//添加插入列
					s1.append(getTbColumn(key));
					//添加插入值
					s2.append("'"+map.get(key)+"'");
					//设置为true,可以添加逗号
					b = true;
				}
				//添加结束的)
				s1.append(")");
				s2.append(")");
				//最后进行拼接
				sb.append(s1).append(" values ").append(s2);
				
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return sb.toString();
		
	}
	
	
	//自动拼接更新语句
	public static String getUpdate(Object obj,String tableName){
		//update t_im_user set login_name='' user_name='' where id = ''
		StringBuilder sb = new StringBuilder();
		try {
			//获取需要更新map字段集合
			Map<String, Object> map = beanToMap(obj);
			//判断是否有要更新的字段
			if(map.keySet().size()>0){
				boolean b = false;
				sb = new StringBuilder("update "+ tableName+ " set ");
				//遍历map
				for(String key:map.keySet()){
					//判断是否要加入逗号
					if(b) sb.append(",");
					//拼接语句
					sb.append(getTbColumn(key)+" = '"+map.get(key)+"' ");
					//可以添加逗号
					b = true;
				}
				//拼接最后的更新条件，id一定会存在，因为更新需要id
				sb.append(" where id = "+map.get("id"));
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return sb.toString();
	}
	
	
	public static String[] getTips(Date date){
		String []result = new String[2];
		String tips = "";
		String color = "";
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Calendar c1 = Calendar.getInstance();
			long hours = c1.get(Calendar.HOUR_OF_DAY);
			long days = c1.get(Calendar.DAY_OF_YEAR);
			Calendar c2 = Calendar.getInstance();
			c2.setTime(date);
			long l = 
				c1.getTimeInMillis()-c2.getTimeInMillis();
			long minu = 60*1000L;
			long r = l/minu;
			if(r>=0&&r<=10){
				tips = "刚刚";
				color = "success";
			}else if(r<=59){
				tips = r+"分钟前";
				color = "primary";
			}else if(r/60<hours){
				tips = (r/60)+"小时前";
				color = "info";
			}else if(r/60>=hours&&r/(60*24)<=1){
				tips = "1天前";
				color = "warning";
			}else if(r/(60*24)>1&&r/(60*24)<=days){
				sdf = new SimpleDateFormat("MM-dd");
				tips = sdf.format(date);
				color = "danger";
			}else{
				tips = sdf.format(date);
				color = "danger";
			}
			result[0] = tips;
			result[1] = color;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	

}
